import Vue from 'vue';
import VueRouter from 'vue-router';
import iView from 'view-design';
import frameOut from "./frameOut";
import frameIn from "./frameIn";
import boardPath from "./boardPath";
Vue.use(VueRouter);

let pageList = []
const handleFrameOut=function(setting,store){
    let map= frameOut.map(item=>{
        if(item.path==='/login'){
            item['component']=()=>import(`public/layout/login/${setting.frame.login}`)
        };
        return item;
    });
    //处理需要全屏的看板
    let menu=store.state.admin.layout.menu;
    map = [...map,...handleFullScreen(menu,[])]
    return map;
}
const handleFrameIn=function(setting,store){
    frameIn[0]['component']=()=>import(`public/layout/frame/${setting.frame.layout}`);
    let menu=store.state.admin.layout.menu;
    let children=!!frameIn[0].children?frameIn[0].children:[];
    frameIn[0]['children']=handleChildren(menu,[]).concat(children);
    return frameIn;
}

const handleChildren=function(menu,array){
    menu.map(item=>{
        //需要全屏的看板
        if(boardPath.includes(item.path)) return;
        if(!!item.children&&item.children.length>0){
            array=handleChildren(item.children,array);
        }else{
            if(!item.redirect&&!!item.path && (
                pageList.includes('.' + item.path + '.vue') || pageList.includes('.' + item.path + '/index.vue')
            )) {
                item['component'] = () => import(`@/pages${item.path}`);
                if (item.path.indexOf('/simpleChart') === 0) {
                    item['component'] = () => import(`@/pages/energy/simpleChart`);
                }
                array.push(item)
            }
        }
    });
    return array;
}

//处理需要全屏的看板
const handleFullScreen = function(menu,array){
    menu.map(item=>{
        if(!!item.children&&item.children.length>0){
            array=handleFullScreen(item.children,array);
        }else{
            if(!item.redirect&&!!item.path&&boardPath.includes(item.path)) {
                item['component'] = () => import(`@/pages${item.path}`);
                array.push(item)
            }
        }
    });
    return array;
}

const getPageList = function() {
    let res = {}
    const requireComponent = require.context(
        // 其组件目录的相对路径
        '../pages',
        // 是否查询其子目录
        true,
        // 匹配基础组件文件名的正则表达式
        /\w+\.(vue)$/
    )
    return requireComponent.keys().filter(item => {
        return !/^\.\/(components|config)/g.test(item)
    })
}

// 导出路由 在 main.js 里使用
const getRouter=function(Setting,store){
    pageList = getPageList()
    // console.log("file: index.js:82  getRouter  pageList:", pageList)
    let router = new VueRouter({
        routes:[...handleFrameOut(Setting,store),...handleFrameIn(Setting,store)],
        mode: Setting.routerMode,
        base: Setting.routerBase
    });

    /**
     * 路由拦截
     * 权限验证
     */
    router.$addRoutes = function (params){
       //  router.matcher = new VueRouter(
       //      {
       //          routes:[...frameIn,...frameOut],
       //          mode: router.options.mode,
       //          base: router.options.base
       //      }
       //  ).matcher;
        let routes = router.getRoutes();
        let curRoute = routes.find(item => {
            return item.name === params.name
        })
        if(!!curRoute) return;
        router.addRoute("StarCloud",params)
    }

    // router.$addRoutes = params => {
    //     router.matcher = new VueRouter({
    //         routes: router.options.routes
    //         // 关键代码
    //     }).matcher;
    //     router.addRoute(params);
    // };

    // router.$addChildRoutes = function (parent,route){
    //     router.matcher = new VueRouter(
    //         {
    //             routes:[...frameOut,...error],
    //             mode: router.options.mode,
    //             base: router.options.base
    //         }
    //     ).matcher;
    //     router.addRoute(parent,route)
    // }

    router.beforeEach((to, from, next) => {
        iView.LoadingBar.start();
        next();
    });

    router.afterEach(to => {
        iView.LoadingBar.finish();
        // 多页控制 打开新的页面
        if(!!to.meta&&to.meta.menu){
            console.log("file: index.js:126  to:", to)
            store.dispatch('admin/layout/addPage', to);
        }
        // 更改标题
        let subtitle=!!to.meta.title?'-'+to.meta.title[store.state.locale]:'';
        window.document.title=store.state.setting.frame.title[store.state.locale]+subtitle;
        // 返回页面顶端。
        window.scrollTo(0, 0);
    });
    return router;
}

export  {getRouter,handleChildren};
